package com.study.signin_demo2.class03;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author whx
 * @date 2022/2/21
 */
public class C09_stream {

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        User user1 = new User(1L,"mike",23);
        User user2 = new User(2L,"benjamin",25);
        User user3 = new User(3L,"ben",25);
        User user4 = new User(4L,"mick",23);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        // 1 过滤
        // 查找用户集合中年龄大于24的用户数据
        List<User> newList = new ArrayList<>();
        for (User user : userList) {
            if (user.getAge() != null && user.getAge() > 24){
                newList.add(user);
            }
        }
        System.out.println("过滤----");
        // stream实现
        List<User> collect = userList.stream().filter(user -> user.getAge() > 24).collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("映射----");
        // 2 映射
        // 查找用户集合中ID集合
        List<Long> idList = userList.stream().map(User::getId).collect(Collectors.toList());
        System.out.println(idList);
        System.out.println("排序、分页----");

        // 3 排序、分页
        // 查找用户中年龄最小的前3个用户
        List<User> collect1 = userList.stream().sorted(Comparator.comparingLong(User::getAge)).limit(3).collect(Collectors.toList());
        System.out.println(collect1);
        System.out.println("去重----");
        // 4 去重
        userList.add(user1);
        List<User> collect2 = userList.stream().sorted(Comparator.comparingLong(User::getAge)).limit(3).collect(Collectors.toList());
        Set<User> collect3 = userList.stream().sorted(Comparator.comparingLong(User::getAge)).limit(3).collect(Collectors.toSet());
        System.out.println(collect2);
        System.out.println(collect3);
        // 5 统计
        int sum = userList.stream().mapToInt(User::getAge).sum();
        System.out.println("年龄："+sum);


    }
}
